const app = getApp()
import { getStorage } from "../../utils/localStorage"
import {
  focusActivities, activityOption, activity_BindUserDynamic, activityGive_option, dynamiGive_option, dynamiCollection_option, listSwiper,
  listPopularDetions
} from "../../api/homePage"
import { baseUrl } from "../../api/request"
import { getMapDistance } from "../../utils/address"
Component({
  data: {
    //自定义导航栏组件参数
    navData: {
      level: 3,
      title: '首页'
    },
    baseUrl: baseUrl,
    gzFlag: true,
    swiper: {
      autoplay: true,  //自动切换
      dots: true,  //指示点
      dotsColor: "#ffffff", //指示点颜色
      dotsActiveColor: "#4646A0",//选中指示点颜色
      circular: true, //衔接滑动
      duration: 3000, //滑动动画时长
      boxFlag: true,
    },
    labelList: [],
    acyObj: {},
    triggered:false,
    listQuery: {
      activityId: "",
      pageSize: 5,
      pageNum: 1,
      userId: getStorage("user").id,
    },
    total: 0, //列表总页数
    showPull: true, //上拉加载更多状态
    list: [],
    rmUserList: [],
    user: null,
    latlng: {},
    jsAcyObj: {},
    activityData: {}, //活动信息对象集合
    UserDynamicsList: [], //用户动态列表
    pageTop: app.globalData.navHeight + app.globalData.navTop,
    pageBottom: app.globalData.bottomLift - 12,
    boxTop: 0,
    //活动模块头部nav切换栏索引
    hdNavIndex: 0,
    //功能按钮列表
    funcutList: [
      {
        icon: "../../image/icon/xiangcunhuodong.png",
        title: "乡村活动",
        url: ""
      },
      {
        icon: "../../image/icon/luxianguihua.png",
        title: "路线规划",
        url: ""
      },
      {
        icon: "../../image/icon/lvyouxiangzhen.png",
        title: "旅游乡镇",
        url: ""
      },
      {
        icon: "../../image/icon/xiangcuntechan.png",
        title: "乡村特产",
        url: ""
      }
    ],
    //热门目的地
    popularDesionsList: [],
    //轮播图列表
    swiperList: [],
    //轮播图索引
    swiperIndex: 0,

  },
  lifetimes: {
    attached() {
      if (app.loginState()) return;
      this.setData({
        user: getStorage("user"),
        latlng: getStorage("latLng"),
        "listQuery.userId": getStorage("user").id
      });
      this.getSwiperList();
      this.getPopularDetionsList();
      this.getActivities_list();
    },
    detached() {
    },
  },
  pageLifetimes: {
    show: function () {
      if (getStorage('activityId')) {
        this.setData({ "listQuery.activityId": getStorage('activityId'), "listQuery.pageNum": 1, UserDynamicsList: [] });
        this.getActivities_list();
      };
      //动态点赞静态处理
      let dynamicId = app.globalData.dynamicId, dynamicGive = app.globalData.dynamicGive, dynamicGiveNum = app.globalData.dynamicGiveNum,
        dynamicCtion = app.globalData.dynamicCtion, dynamicCtionNum = app.globalData.dynamicCtionNum,
        dynamicMent = app.globalData.dynamicMent;
      if (dynamicId) {
        let index = this.data.UserDynamicsList.findIndex(item => { return item.id === dynamicId }),
          likeValue = "UserDynamicsList[" + index + "].likeState",
          likeNum = "UserDynamicsList[" + index + "].likeNumber",
          ctionValue = "UserDynamicsList[" + index + "].collectionState",
          ctionNum = "UserDynamicsList[" + index + "].collectionNumber",
          commentNum = "UserDynamicsList[" + index + "].commentNumber";
        this.setData({
          [likeValue]: dynamicGive === 1 ? true : false,
          [likeNum]: dynamicGiveNum,
          [ctionValue]: dynamicCtion === 1 ? true : false,
          [ctionNum]: dynamicCtionNum,
          [commentNum]: dynamicMent,
        });
      };
      //活动点赞静态处理
      let activityId = app.globalData.activityId,
        activityGive = app.globalData.activityGive,
        activityGiveNum = app.globalData.activityGiveNum,
        activityCtion = app.globalData.activityCtion,
        activityCtionNum = app.globalData.activityCtionNum,
        activityMent = app.globalData.activityMent,
        signUpNum = app.globalData.signUpNum;
      if (activityId) {
        let likeValue = "activityData.likeState",
          likeNum = "activityData.likeNumber",
          ctionValue = "activityData.collectionState",
          ctionNum = "activityData.collectionNumber",
          commentNum = "activityData.commentNumber",
          signNum = "activityData.peopleNumber";
        this.setData({
          [likeValue]: activityGive === 1 ? true : false,
          [likeNum]: activityGiveNum,
          [ctionValue]: activityCtion === 1 ? true : false,
          [ctionNum]: activityCtionNum,
          [commentNum]: activityMent,
          [signNum]: signUpNum
        });
      };
    }
  },

  methods: {

    //搜索框点击事件
    searchTap() {
      wx.navigateTo({
        url: '/pagesShouYe/pages/searchAll/index',
      });
    },

    /** 获取轮播图数据 */
    getSwiperList() {
      listSwiper().then(res => {
        this.setData({ swiperList: res.data.data });
      });
    },

    /* 轮播图swiper组件 change事件 */
    swiperChange(e) {
      const index = e.detail.current;
      this.setData({
        swiperIndex: index
      });
    },

    // 下拉刷新
    refresh(){
      this.data.listQuery.pageNum=1;
      this.setData({
        UserDynamicsList:[]
      })
      this.getPopularDetionsList()
      this.getActivities_list()
    },

    /** 获取热门目的地列表 */
    getPopularDetionsList() {
      const _this = this.data, city = _this.user.townShipName.split(",")[1];
      listPopularDetions({ city: city }).then(res => {
        let arr = res.data.data.map(item => ({
          ...item,
          villageImage: item.villageImage ? item.villageImage.split(",") : []
        }));
        this.setData({
          popularDesionsList: arr
        });
      });
    },

    //获取活动列表数据 
    getActivities_list() {
      let that = this.data;
      focusActivities({ userId: that.user.id, activityId: this.data.listQuery.activityId }).then(res => {
        const { data } = res.data;
        data.imageScale = data.imageScale ? data.imageScale.split(",") : [];
        data.distance = getMapDistance(that.latlng.lat, that.latlng.lng, data.latitude, data.longitude);
        this.setData({
          triggered:false,
          activityData: data,
          "listQuery.activityId": data.id ? data.id : "",
        });
        this.getUserDynamics_list();
      });
    },

    //获取用户动态列表信息
    getUserDynamics_list() {
      let that = this.data;
      activity_BindUserDynamic(that.listQuery).then(res => {
        res.data.data.list.forEach(item => {
          item.imageScale = item.imageScale.split(",");
          item.randowNum = this.randomFun(0, (item.imageScale.length - 1));
          item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
        });
        this.setData({
          UserDynamicsList: [...that.UserDynamicsList, ...res.data.data.list],
          total: Math.ceil(res.data.data.total / that.listQuery.pageSize)
        });
      });
    },

    //搜索input框 blur事件
    searchBlur(e) {
      const value = e.detail.value;
      console.log(value, 'value');
    },

    //轮播图列表点击事件
    swiperListTap(e) {
      const item = e.currentTarget.dataset.item;
      if (item.pathUrl) {
        if(item.status){
          console.log('/pages/webView?url='+encodeURIComponent(item.pathUrl))
          wx.navigateTo({
            url: '/pages/webView/webView?url='+encodeURIComponent(item.pathUrl),
          });
        }else{
          wx.navigateTo({
            url: item.pathUrl,
          });
        }
        
      };
    },

    //功能按钮列表点击事件
    funcutTap(e) {
      let item = e.currentTarget.dataset.item;
      switch (item.title) {
        case "乡村活动":
          this.triggerEvent("tabFooter", 6);
          break;
        case "路线规划":
          this.triggerEvent("tabFooter", 2);
          //    wx.navigateTo({
          //      url: '/pages/luxian/index',
          //    })
          break;
        case "旅游乡镇":
          wx.navigateTo({
            url: '/pages/township/index',
          });
          break;
        case "乡村特产":
          wx.navigateTo({
            url: '/pagesShangping/pages/index/index',
          });
          break;
      };
    },

    //热门目的地列表点击事件
    rmdddListTap(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/xaingcunDetail/index?id=' + item.villageId,
      });
    },

    //热门目的地更多按钮点击事件
    remmdMoreTap() {
      const _this = this.data;
      wx.navigateTo({
        url: '/pagesShouYe/pages/xiangCun/index?longitude=' + _this.latlng.lng + '&latitude=' + _this.latlng.lat,
      });
    },

    //最新活动更多按钮点击事件
    zxhdMore() {
      wx.navigateTo({
        url: '/pagesHuodong/pages/index/index',
      });
      console.log("最新活动更多按钮点击事件");
    },

    //精选游记更多按钮点击事件
    jxyjMore() {
      wx.navigateTo({
        url: '/pages/indexNav/index',
      });
      console.log("精选游记更多按钮点击事件");
    },
    //随机数
    randomFun(start, end) {
      return Math.round(Math.random() * (end - start) + start)
    },
    //选择活动点击事件
    xzBox() {
      wx.navigateTo({
        url: '/pagesHuodong/pages/index/index',
      })
    },
    //选择活动弹窗里的列表点击事件
    // choiceList(e) {
    //     let item = e.currentTarget.dataset.item;
    //     this.setData({
    //         activityData: item,
    //         "listQuery.activityId": item.id,
    //         "listQuery.pageNum": 1,
    //         UserDynamicsList: [],
    //     });
    //     this.getUserDynamics_list();
    //     this.setData({
    //         boxTop: 0,
    //     });
    // },
    //关闭选择活动弹窗
    closeHuodongxz() {
      this.setData({
        boxTop: 0
      });
    },
    //baner图点击事件
    bannerClick(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/bnnerDetailMore/index?id=' + item.id,
      })
    },
    //列表详情
    detail(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/listDetail/index?id=' + item.id + '&dynamicType=用户动态',
      })
    },
    //活动点赞图标事件
    async collectionClick(e) {
      app.globalData.dynamicId = null;
      let that = this.data;
      let item = e.detail;
      let flag = !item.likeState ? true : false;
      activityGive_option({ userId: that.user.id, activityId: item.id, state: flag }).then(res => {
        let state = "activityData.likeState",
          index = "activityData.likeNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [index]: !flag ? item.likeNumber - 1 : item.likeNumber + 1
          });
        };
      });
    },
    //活动收藏图标点击事件
    collectionTap(e) {
      app.globalData.dynamicId = null;
      let that = this.data,
        item = e.detail,
        flag = !item.collectionState ? true : false;
      activityOption({ userId: that.user.id, activityId: item.id, state: flag }).then(res => {
        let state = "activityData.collectionState",
          num = "activityData.collectionNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [num]: !flag ? item.collectionNumber - 1 : item.collectionNumber + 1
          });
        };
      });
    },
    //用户动态点赞或取消点赞事件
    commentClick(e) {
      app.globalData.activityId = null;
      let that = this.data,
        item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        flag = !item.likeState ? true : false;
      dynamiGive_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
        let state = "UserDynamicsList[" + index + "].likeState";
        let num = "UserDynamicsList[" + index + "].likeNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
          });
        };
      });
      // if (res.data.code === 200) {
      //     let colleStatus = "list[" + index + "].colleStatus";
      //     let colleNum = "list[" + index + "].colleNum";
      //     let scNum = 0;
      //     if (res.data.data === 1) {
      //         scNum = _this.list[index].colleNum + 1;
      //     } else {
      //         scNum = _this.list[index].colleNum - 1;
      //     };
      //     this.setData({
      //         [colleStatus]: res.data.data,
      //         [colleNum]: scNum,
      //     });
      // };
    },
    //用户动态收藏图标按钮事件
    scTap(e) {
      app.globalData.activityId = null;
      let that = this.data;
      let item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        flag = !item.collectionState ? true : false;
      dynamiCollection_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
        let state = "UserDynamicsList[" + index + "].collectionState",
          num = "UserDynamicsList[" + index + "].collectionNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [num]: flag ? item.collectionNumber + 1 : item.collectionNumber - 1
          });
        };
      });
    },
    //搜索图标点击事件
    searchClick() {
      wx.navigateTo({
        url: '/pagesShouYe/pages/search/index',
      })
    },
    /* 上拉加载更多 */
    pullUp(e) {
      let that = this.data;
      if ((that.listQuery.pageNum + 1) <= that.total) {
        this.setData({
          showPull: false,
          "listQuery.pageNum": that.listQuery.pageNum += 1
        });
        this.getUserDynamics_list();
      } else {
        this.setData({
          showPull: true
        });
      };
    },
  },
})